package org.jeecg.modules.wlhy.hydriver.service.impl;


import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.modules.paycenter.channel.bankdocking.dto.RespPacket;
import org.jeecg.modules.paycenter.channel.bankdocking.utils.BankUtils;
import org.jeecg.modules.wlhy.hyconfig.entity.HyConfig;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriverAccountBook;
import org.jeecg.modules.wlhy.hydriver.mapper.HyDriverAccountBookMapper;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverAccountBookService;
import org.jeecg.modules.wlhy.utils.HyConfigUtils;
import org.jeecg.modules.wlhy.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Description: hy_driver_account_book
 * @Author: jeecg-boot
 * @Date:   2021-01-16
 * @Version: V1.0
 */
@Service
public class HyDriverAccountBookServiceImpl extends ServiceImpl<HyDriverAccountBookMapper, HyDriverAccountBook> implements IHyDriverAccountBookService {

    @Autowired
    private BankUtils bankUtils;

    @Autowired private UserUtil userUtil;

    @Override
    public Map getAccountBookInfo() {
        HyDriver driver = userUtil.getDriver();
        //是否开通过
        HyDriverAccountBook accountBook = this.getAccountBookByDriverId(driver.getId());
        if(accountBook == null){
            return null;
        }
        Map<String,Object> data = new HashMap<>();
        accountBook.setPayPwd("");
        data.put("accountBook" , accountBook);
        data.put("info" , null);
        //获取账簿余额信息
        try {
            RespPacket packet = bankUtils.getAccountBookBalance(accountBook.getAccNo(), accountBook.getProv(), accountBook.getLogAccNo());
            if(packet.isSuccess()){
                data.put("info" , packet.getAcc());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return data;
    }

    @Override
    @Transactional
    public void addAccountBook(HyDriverAccountBook hyDriverAccountBook,HyDriver driver) {
        HyConfig config = HyConfigUtils.getConfig();
        if(!config.getNhbankIzUse()){
            throw new JeecgBootException("未开通服务");
        }
        String logAccNo =  this.createDriverLogAccNo();
        String logAccName = driver.getDriverName();
        hyDriverAccountBook.setDriverId(driver.getId());
        hyDriverAccountBook.setUserId(driver.getUserId());
        hyDriverAccountBook.setAccNo(config.getNhbankAccno());
        hyDriverAccountBook.setProv(config.getNhbankProv());
        hyDriverAccountBook.setLogAccName(driver.getDriverName());
        hyDriverAccountBook.setLogAccNo(logAccNo);
//        hyDriverAccountBook.setCrLogAccNo("0000000000");
//        hyDriverAccountBook.setLogAccNoGr("");
        String payPwd = hyDriverAccountBook.getPayPwd();
        String encryptPayPwd = PasswordUtil.encrypt(logAccNo, payPwd,  PasswordUtil.BSalt);
        hyDriverAccountBook.setPayPwd(encryptPayPwd);
        if( this.save(hyDriverAccountBook)){
            try {
                RespPacket packet = bankUtils.AddAccountBook(logAccName, logAccNo);
                if(!packet.isSuccess()){
                    throw new JeecgBootException(packet.getRespInfo());
                }
            } catch (Exception e) {
                throw new JeecgBootException(e.getMessage());
            }
        }else {
            throw new JeecgBootException("添加失败");
        }
    }

    @Override
    public void editPayPwd(String oldPwd, String password) {
        HyDriver driver = userUtil.getDriver();
        HyDriverAccountBook accountBook = this.getOne(
                new QueryWrapper<HyDriverAccountBook>().eq("driver_id", driver.getId())
        );
        if(accountBook == null){
            throw new JeecgBootException("未获取到账户信息");
        }
        String encryptPayPwd = PasswordUtil.encrypt(accountBook.getLogAccNo(), oldPwd,  PasswordUtil.BSalt);
        if(!StringUtils.equals(encryptPayPwd,accountBook.getPayPwd())){
            throw new JeecgBootException("原始支付密码错误");
        }
        String newEncryptPayPwd = PasswordUtil.encrypt(accountBook.getLogAccNo(), password,  PasswordUtil.BSalt);
        accountBook.setPayPwd(newEncryptPayPwd);
        if(!this.updateById(accountBook)){
            throw new JeecgBootException("修改失败");
        }
    }

    @Override
    public void ResetPayPwd(String password) {
        HyDriver driver = userUtil.getDriver();
        HyDriverAccountBook accountBook = this.getOne(
                new QueryWrapper<HyDriverAccountBook>().eq("driver_id", driver.getId())
        );
        if(accountBook == null){
            throw new JeecgBootException("未获取到账户信息");
        }
        String newEncryptPayPwd = PasswordUtil.encrypt(accountBook.getLogAccNo(), password,  PasswordUtil.BSalt);
        accountBook.setPayPwd(newEncryptPayPwd);
        if(!this.updateById(accountBook)){
            throw new JeecgBootException("修改失败");
        }
    }

    @Override
    public HyDriverAccountBook getAccountBookByDriverId(String driverId) {
        HyDriverAccountBook accountBook = this.getOne(
                new QueryWrapper<HyDriverAccountBook>().eq("driver_id", driverId)
        );
        return accountBook;
    }


    @Override
    public String createDriverLogAccNo() {
        for (int i = 0; i < 10; i++) {
            //todo
            String logAccNo =  "3" + RandomUtil.randomNumbers(9);
            int count = this.count(new QueryWrapper<HyDriverAccountBook>().eq("log_acc_no",logAccNo));
            if(count == 0) {
                return logAccNo;
            }
        }
        throw new JeecgBootException("生成失败，请重试");
    }

    @Override
    public List<HyDriverAccountBook> getAccountBookByDriverIds(Set<String> driverSet) {
        List<HyDriverAccountBook> accountBooks = this.list(
                new QueryWrapper<HyDriverAccountBook>().in("driver_id", driverSet)
        );
        return accountBooks;
    }
}
